package cn.group.controller;

import cn.group.mapper.LoginMapper;
import cn.group.service.LoginService;
import cn.group.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.entity.Manager;
import pojo.entity.Record;
import pojo.entity.User;
import utils.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(tags = "用户登录")
@Controller
@RequestMapping(value = "/login" , produces = "text/html;charset=UTF-8")
public class LoginController extends BaseController {

    @Autowired
    private LoginService loginService;

    @ApiOperation("用户登录验证")
    @RequestMapping(value = "/check.do")
    @ResponseBody
    public String checkUser(String userName, String password, HttpServletRequest request, HttpServletResponse response){
        //获取当前用户（获得一个用户）
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据（给用户《令牌》）
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try {
            //验证令牌（login通过自定义的realm进行认证）
            subject.login(token);//执行登录的方法

            //获得登录成功后的user对象
            Manager user = loginService.findUserByName(userName);
            System.out.println("登录的用户："+user.toString());
            String userJson = writerSuccessResult(user, response);
            return userJson;
        }catch (UnknownAccountException e){
            return writerErrorResult("用户名错误！", response);
        }catch (IncorrectCredentialsException e){
            return writerErrorResult("密码错误！", response);
        }catch (DisabledAccountException e){
            return writerErrorResult("账号被冻结！", response);
        }
    }

    @ApiOperation("用户注册")
    @RequestMapping(value = "/register.do")
    @ResponseBody
    public String Register(String userName,String password,String email){
        String md5 = new SimpleHash("MD5", password, null, 3).toHex();
        Manager user=new Manager(userName,md5,email,100,"");
        System.out.println(user);
        loginService.saveUser(user);
        return writerSuccessResult(user);
    }
}
